package edu.zju;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import edu.zju.db.MysqlUtil;

public class SensorDataFetcher {
	public static void main(String args[]){
		selectSensorData(2+"");
	}

	public static Map<String,String> selectSensorData(String usbPort) {
		String lightStr = "";
		String humStr = "";
		String temStr = "";
		String timeStr = "";
		
		int maxrow = 20;
		SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
		String curtime = formater.format(new java.util.Date());
		String tableName = "sensor" + usbPort;
		String sql = "select * from sensor" + usbPort
				+ " order by time desc limit " + maxrow;

		Connection connection = MysqlUtil.getConnection();
		Statement statement = null;
		ResultSet rs = null;
		
		try {
			statement = connection.createStatement();
			rs = statement.executeQuery(sql);
			
			while (rs.next()){
				int id = rs.getInt(1);
				int humtemp = rs.getInt(3);
				String time = rs.getString(6);
				int temtemp = rs.getInt(4);
				int light = rs.getInt(5);
				
				lightStr += light + ",";
				humStr += changehum(humtemp) + ",";
				temStr += changetem(temtemp) + ",";
				timeStr += time +",";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		MysqlUtil.close(connection, statement, rs);
		
		Map<String,String> map = new HashMap<String,String>();
		map.put("light", lightStr);
		map.put("hum", humStr);
		map.put("tem", temStr);
		map.put("time",timeStr);
//		System.out.println(map);
		return map;
//		System.out.println(lightStr);
//		System.out.println(humStr);
//		System.out.println(temStr);
	}
	
	public static float changehum(int humtemp) {
		float hum = humtemp * 0.0367f;
		hum -= 2.0468;
		if (hum > 100) {
			hum = 100;
		}
		return hum;
	}

	public static float changetem(int temtemp) {
		float tem = temtemp / 10 - 400;
		tem = tem / 10;
		tem = tem / 4 + tem;
		return tem;
	}
}
